package com.googlecode.agscrum.controller.jsf.bean;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.googlecode.agscrum.model.entity.Product;
import com.googlecode.agscrum.model.entity.Team;
import com.googlecode.agscrum.model.entity.User;
import com.googlecode.agscrum.model.service.Service;
import com.googlecode.agscrum.model.util.Criteria;
import com.googlecode.agscrum.model.util.Restrictions;

@Controller("teamControllerBean")
@Scope("request")
@Configurable(autowire = Autowire.BY_NAME)
public class TeamControllerBean extends BaseControllerBean<Team, Long> {

	private Service<Team, Long> teamService;

	public void setTeamService(Service<Team, Long> teamService) {
		this.teamService = teamService;
	}

	private Service<User, Long> userService;

	public void setUserService(Service<User, Long> userService) {
		this.userService = userService;
	}

	private List<User> users;

	private List<User> selectedUsers;

	@Override
	protected void reset() {
		users = null;
		selectedUsers = null;
	}

	@Override
	protected Criteria getCriteria() {
		Criteria criteria = Criteria.getInstance("Team.searchQuery",
				Team.class);
		criteria.addAnd(Restrictions.ilike("t.name", true, getEntity()
				.getName(), true));
		return criteria;
	}

	@Override
	protected Service<Team, Long> getService() {
		return teamService;
	}

	public void setSelectedUsers(List<User> selectedUsers) {
		this.selectedUsers = selectedUsers;
	}

	public List<User> getSelectedUsers() {
		return selectedUsers;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	@Override
	protected void beforeSave() {
		getEntity().changeUsers(selectedUsers);
		super.beforeSave();
	}

	@Override
	public String save() {
		return super.save();
	}

	@Override
	public void setEntity(Team entity) {
		if (entity != null && entity.getId() != null) {
			selectedUsers = entity.getUsers();
		}
		super.setEntity(entity);
	}

	public List<User> getUsers() {
		users = userService.findAll();
		List<User> filterTeams = new ArrayList<User>();
		if (getEntity().getId() != null) {
			for (User user : users) {
				if (selectedUsers == null || !(selectedUsers.contains(user))) {
					filterTeams.add(user);
				}
			}
			users = filterTeams;
		}
		return users;
	}
}
